package cn.larry.tools.string;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * This is created,
 * but not necessarily updated by me.
 * Therefore, AUTHOR is useless.
 * 2022/12/30 20:39
 *
 * @Version 1.0
 */
public class ImgTxtUtils {

    /**
     * 生成手机号图片
     *
     * @param phoneNum
     * @return
     */
    public static BufferedImage getPhoneNumStringPic(String phoneNum) {
        return drawTranslucentStringPic(200, 40, 28, phoneNum);
    }

    /**
     * 绘制透明背景的文字图片
     */
    public static BufferedImage drawTranslucentStringPic(int width, int height, Integer fontHeight, String drawStr) {
        try {
            BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D gd = buffImg.createGraphics();
            //设置透明  start
            buffImg = gd.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
            gd = buffImg.createGraphics();
            //设置透明  end
            gd.setFont(new Font("宋体", Font.PLAIN, fontHeight)); //设置字体
            gd.setColor(Color.black); //设置颜色
//            gd.drawRect(0, 0, width - 1, height - 1); //画边框
            gd.drawString(drawStr, 0, fontHeight); //输出文字（中文横向居中）
            return buffImg;
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 获取水印文字的长度
     *
     * @param waterMarkContent
     * @param g
     * @return
     */
    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }

    /**
     * 图片添加水印
     *
     * @param srcImg
     * @return
     */
    public static BufferedImage addWatermark(Image srcImg) {
        //获取图片的宽
        int srcImgWidth = srcImg.getWidth(null);
        //获取图片的高
        int srcImgHeight = srcImg.getHeight(null);
        System.out.println("图片的宽:" + srcImgWidth);
        System.out.println("图片的高:" + srcImgHeight);

        BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
        // 加水印
        //创建画笔
        Graphics2D g = bufImg.createGraphics();
        //绘制原始图片
        g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
        //-------------------------文字水印 start----------------------------
        //根据图片的背景设置水印颜色
        g.setColor(new Color(255, 255, 255, 128));
        //设置字体  画笔字体样式为微软雅黑，加粗，文字大小为60pt
        g.setFont(new Font("宋体", Font.BOLD, 60));
        //水印内容
        String waterMarkContent = "新余便民";
        //设置水印的坐标(为原图片中间位置)
        int x = (srcImgWidth - getWatermarkLength(waterMarkContent, g)) / 2;
        int y = srcImgHeight / 2;
        //画出水印 第一个参数是水印内容，第二个参数是x轴坐标，第三个参数是y轴坐标
        g.drawString(waterMarkContent, x, y);
        g.dispose();
        //-------------------------文字水印 end----------------------------
        return bufImg;
    }

}
